package com.clean.cleantotal.utils

import android.graphics.Bitmap
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ImageUtils
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.entity.LocalMediaFolder
import com.luck.picture.lib.interfaces.OnQueryDataSourceListener
import java.util.Locale

object CompressUtils {
    fun getAllPhotos(
        fragment: Fragment, filterFolder: String, call: OnQueryDataSourceListener<LocalMedia>
    ) {
        PictureSelector.create(fragment).dataSource(SelectMimeType.ofImage())
            .setQueryFilterListener { media: LocalMedia -> filterFolder == media.parentFolderName }
            .obtainMediaData(call)
    }

    fun getCompressedPhotos(
        fragment: Fragment, call: OnQueryDataSourceListener<LocalMediaFolder>
    ) {
        PictureSelector.create(fragment).dataSource(SelectMimeType.ofImage()).isPageStrategy(false)
            .obtainAlbumData(call)
    }

    fun getCompressedImage(image: Bitmap?, quality: Int, path: String): Bitmap? {
        if (path.lowercase(Locale.getDefault()).endsWith("png")) {
            return image
        } else {
            val imageByte = ImageUtils.compressByQuality(image, quality, false)
            return ImageUtils.bytes2Bitmap(imageByte)
        }
    }

    fun getQ(path: String): Int {
        return if (path.lowercase(Locale.getDefault()).endsWith("png")) {
            100
        } else {
            50
        }
    }

    fun getFormat(path: String): Bitmap.CompressFormat {
        if (path.lowercase(Locale.getDefault()).endsWith("png")) {
            return Bitmap.CompressFormat.PNG
        } else return if (path.lowercase(Locale.getDefault()).endsWith("webp")) {
            Bitmap.CompressFormat.WEBP
        } else {
            Bitmap.CompressFormat.JPEG
        }
    }

    fun getCompressedImageSize(image: Bitmap?, quality: Int, path: String): Long {
        return if (path.lowercase(Locale.getDefault()).endsWith("png")) {
            FileUtils.getLength(path)
        } else {
            val imageByte = ImageUtils.compressByQuality(image, quality, false)
            imageByte.size.toLong()
        }
    }

    fun saveCompressPhoto(
        image: Bitmap?, savePath: String?, format: Bitmap.CompressFormat?, quality: Int
    ): Boolean {
        val isSuccess = ImageUtils.save(image, savePath, format, quality)
        if (isSuccess) {
            FileUtils.notifySystemToScan(savePath)
        }
        return isSuccess
    }
}